using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

internal class MainBehaviour : MonoBehaviour
{
    // TO-DO LIST
    // TODO - RH - Make UI graphics to replace Unity GUI Buttons

    private bool internetAvailability = false;

    // Use this for initialization
    private void Start()
    {
    }

    // Update is called once per frame
    private void Update()
    {
    }

    private void OnGUI()
    {
        var titleRect = new Rect(Screen.width*.5f - 58.5f, Screen.height*.1f - 20f, 119f, 40f);

        var playRect = new Rect(Screen.width*.5f - Screen.width*.327f/2, Screen.height*.3f, Screen.width*.327f,
                                Screen.height*.11f);
        var auctionHouseRect = new Rect(Screen.width*.5f - Screen.width*.327f/2, Screen.height*.45f, Screen.width*.327f,
                                        Screen.height*.11f);
        var socialPageRect = new Rect(Screen.width*.5f - Screen.width*.327f/2, Screen.height*.6f, Screen.width*.327f,
                                      Screen.height*.11f);
        var exitRect = new Rect(Screen.width*.5f - Screen.width*.327f/2, Screen.height*.75f, Screen.width*.327f,
                                Screen.height*.11f);

        GUI.Label(titleRect, "Adventures of Worth");

        if (GUI.Button(playRect, "Play"))
        {
            StartCoroutine(CheckForInternetConnection());
            // TODO - RH - If the user has internet access, ask if the user wants to setup an online account for events/auction house access/friends & social

            if(internetAvailability)
                Application.LoadLevel("InGame");
        }
        else if (GUI.Button(auctionHouseRect, "Auction House"))
        {
            Application.LoadLevel("AuctionHouse");
        }
        else if (GUI.Button(socialPageRect, "Social Page"))
        {
            Application.LoadLevel("Social");
        }
        else if (GUI.Button(exitRect, "Exit"))
        {
            Application.Quit();
        }
    }

    IEnumerator CheckForInternetConnection()
    {
        const float timeout = 10f;
        float startTime = Time.timeSinceLevelLoad;
        // Google.com
        Ping ping = new Ping("74.125.228.3");

        Debug.Log("Checking network...");
        while (true)
        {
            if (ping.isDone)
            {
                Debug.Log("Network available.");
                internetAvailability = true;
                yield break;
            }

            if (Time.timeSinceLevelLoad - startTime > timeout)
            {
                Debug.Log("No network.");
                internetAvailability = false;
                yield break;
            }

            yield return new WaitForEndOfFrame();
        }
    }

}